package com.wwtech.epp.application;

import android.app.ActivityManager;
import android.content.Context;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;

import com.ninjia.ninjiabaselibrary.utils.SpUtil;
import com.socks.library.KLog;
import com.tencent.bugly.crashreport.CrashReport;
import com.wwtech.epp.BuildConfig;
import com.wwtech.epp.R;
import com.wwtech.epp.base.SealAppContext;
import com.wwtech.epp.base.SealUserInfoManager;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.message.TestMessage;
import com.wwtech.epp.message.provider.TestMessageProvider;
import com.wwtech.epp.utils.AppActivityManager;
import com.wwtech.epp.utils.swipeback.ActivityLifecycleHelper;

import io.rong.imageloader.core.DisplayImageOptions;
import io.rong.imageloader.core.display.FadeInBitmapDisplayer;
import io.rong.imkit.RongIM;
import io.rong.imkit.widget.provider.RealTimeLocationMessageProvider;
//import io.rong.recognizer.RecognizeExtensionModule;

//import com.wwtech.epp.message.provider.ContactNotificationMessageProvider;

/**
 * 作者：Android on 2017/8/1
 * 邮箱：365941593@qq.com
 * 描述：
 */

public class AppConfig extends MultiDexApplication {
    public static AppConfig instance;
    //滑动返回
    public ActivityLifecycleHelper mActivityLifecycleHelper;

    public AppActivityManager mAppActivityManager;

    private AppComponent mAppComponent;
    private static DisplayImageOptions options;

    public AppConfig() {

    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        KLog.init(BuildConfig.LOG_DEBUG);
        CrashReport.initCrashReport(this, "066310a240", BuildConfig.LOG_DEBUG);
        setupApplicationComponent();
        registerActivityLifecycleCallbacks(ActivityLifecycleHelper.build());
        mAppActivityManager = new AppActivityManager(this);
        //初始化融云
        RongIM.setServerInfo("nav.cn.ronghub.com", "up.qbox.me");
        RongIM.init(this, SpUtil.getBoolean(this, ContainValue.ENVIRONMENT, true)? "z3v5yqkbz6ma0" : "z3v5yqkbz6ma0");
        SealAppContext.init(this);
        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {

//            LeakCanary.install(this);//内存泄露检测

            /**
             * 注意：
             *
             * IMKit SDK调用第一步 初始化
             *
             * context上下文
             *
             * 只有两个进程需要初始化，主进程和 push 进程
             */
//            Thread.setDefaultUncaughtExceptionHandler(new RongExceptionHandler(this));

            try {
//                RongIM.registerMessageTemplate(new ContactNotificationMessageProvider());
                RongIM.registerMessageTemplate(new RealTimeLocationMessageProvider());
                RongIM.registerMessageType(TestMessage.class);
                RongIM.registerMessageTemplate(new TestMessageProvider());


            } catch (Exception e) {
                e.printStackTrace();
            }
            openSealDBIfHasCachedToken();

            options = new DisplayImageOptions.Builder()
                    .showImageForEmptyUri(R.mipmap.de_default_portrait)
                    .showImageOnFail(R.mipmap.de_default_portrait)
                    .showImageOnLoading(R.mipmap.de_default_portrait)
                    .displayer(new FadeInBitmapDisplayer(300))
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .build();

//            RongExtensionManager.getInstance().registerExtensionModule(new PTTExtensionModule(this, true, 1000 * 60));
//            RongExtensionManager.getInstance().registerExtensionModule(new ContactCardExtensionModule(new IContactCardInfoProvider() {
//                @Override
//                public void getContactAllInfoProvider(final IContactCardInfoCallback contactInfoCallback) {
//                    SealUserInfoManager.getInstance().getFriends(new SealUserInfoManager.ResultCallback<List<Friend>>() {
//                        @Override
//                        public void onSuccess(List<Friend> friendList) {
//                            contactInfoCallback.getContactCardInfoCallback(friendList);
//                        }
//
//                        @Override
//                        public void onError(String errString) {
//                            contactInfoCallback.getContactCardInfoCallback(null);
//                        }
//                    });
//                }
//
//                @Override
//                public void getContactAppointedInfoProvider(String userId, String name, String portrait, final IContactCardInfoCallback contactInfoCallback) {
//                    SealUserInfoManager.getInstance().getFriendByID(userId, new SealUserInfoManager.ResultCallback<Friend>() {
//                        @Override
//                        public void onSuccess(Friend friend) {
//                            List<UserInfo> list = new ArrayList<>();
//                            list.add(friend);
//                            contactInfoCallback.getContactCardInfoCallback(list);
//                        }
//
//                        @Override
//                        public void onError(String errString) {
//                            contactInfoCallback.getContactCardInfoCallback(null);
//                        }
//                    });
//                }
//
//            }, new IContactCardClickListener() {
//                @Override
//                public void onContactCardClick(View view, ContactMessage content) {
//                    Intent intent = new Intent(view.getContext(), UserDetailActivity.class);
//                    Friend friend = SealUserInfoManager.getInstance().getFriendByID(content.getId());
//                    if (friend == null) {
//                        UserInfo userInfo = new UserInfo(content.getId(), content.getName(),
//                                Uri.parse(TextUtils.isEmpty(content.getImgUrl()) ? RongGenerate.generateDefaultAvatar(content.getName(), content.getId()) : content.getImgUrl()));
//                        friend = CharacterParser.getInstance().generateFriendFromUserInfo(userInfo);
//                    }
//                    intent.putExtra("friend", friend);
//                    view.getContext().startActivity(intent);
//                }
//            }));
//            RongExtensionManager.getInstance().registerExtensionModule(new RecognizeExtensionModule());
        }
    }
    /**
     * 分割 Dex 支持
     *
     * @param base
     */
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static synchronized AppConfig getInstance() {
        if (null == instance) {
            instance = new AppConfig();
        }
        return instance;
    }

    public static DisplayImageOptions getOptions() {
        return options;
    }

    protected void setupApplicationComponent() {
        mAppComponent = DaggerAppComponent
                .builder()
                .appModule(new AppModule(this))
                .aPIModule(new APIModule(this))
                .build();
        mAppComponent.inject(this);
    }
    public AppComponent getApplicationComponent() {
        return mAppComponent;
    }

    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    public void openSealDBIfHasCachedToken() {
        String cachedToken = SpUtil.getString(this, ContainValue.LOGINTOKEN, "没有");
        if (!TextUtils.isEmpty(cachedToken)) {
            String current = getCurProcessName(this);
            String mainProcessName = getPackageName();
            if (mainProcessName.equals(current)) {
                SealUserInfoManager.getInstance().openDB();
            }
        }
    }

}
